package com.apimarket.controller;

import com.apimarket.annotation.MultiDSTransactionalAnnotation;
import com.apimarket.dao.RoutePathsMapper;
import com.apimarket.entity.ApiInterface;
import com.apimarket.entity.ApiInterfaceWithBLOBs;
import com.apimarket.entity.Result;
import com.apimarket.entity.kong.Plugin;
import com.apimarket.entity.kong.Route;
import com.apimarket.enums.ExceptionEnum;
import com.apimarket.exception.AMException;
import com.apimarket.service.RouteService;
import com.apimarket.util.RedisUtils;
import com.apimarket.util.kong.KongPlugin;
import com.apimarket.util.kong.KongRoute;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.net.URISyntaxException;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description:
 * @Author ZXR
 * @Date 2021/7/2 16:46
 * @Version 1.0
 */

@RestController
@RequestMapping("/route")
public class RouteController {
    //用父类来接收和他的代理模式有关
    @Autowired
    KongRoute kongRoute;
    @Autowired
    RouteService routeService;
    @Autowired
    RedisUtils redisUtils;
    @Autowired
    private KongPlugin kongPlugin;
    @Autowired
    private RoutePathsMapper routePathsMapper;
    @Value("${redis.route.key}")
    private String routeRedisKey;
    private static final String IO_ERROR = "网络异常";

    @RequestMapping("testAddRouteUnique")
    public Result<String> testAddRouteUnique(@RequestBody @Validated Route route) throws URISyntaxException {
        if(StringUtils.isEmpty((route.getService().getId()))){
            throw new IllegalArgumentException("添加route时必须传入对应service的id");
        }
        List<String> tempPaths=route.getPaths();
        for(String temp:tempPaths){
            if(!temp.startsWith("/"))
                throw new AMException(ExceptionEnum.PATH_MUST_START_WITH_XG);
        }
        if(!route.getMethods().contains("OPTIONS")){
            List<String> methods = route.getMethods();
            methods.add("OPTIONS");
            route.setMethods(methods);
        }
        routeService.addRoutePaths(route);
        return new Result<>("success",200,"success");

    }

    @RequestMapping(value="/add",method = {RequestMethod.POST})
    public Result<String> addRoute(@RequestBody @Validated Route route) throws IOException, URISyntaxException {
        if(StringUtils.isEmpty((route.getService().getId()))){
            throw new IllegalArgumentException("添加route时必须传入对应service的id");
        }
        List<String> tempPaths=route.getPaths();
        for(String temp:tempPaths){
            if(!temp.startsWith("/"))
                throw new AMException(ExceptionEnum.PATH_MUST_START_WITH_XG);
        }
        //往业务数据库中添加路由的path，如果重复会抛异常，需要保证path的全局唯一性
        routeService.addRoutePaths(route);
        try{
            //route.setService(route.new Service(serviceId));
            //Route newRoute=new Route();
            if(!route.getMethods().contains("OPTIONS")){
                List<String> methods = route.getMethods();
                methods.add("OPTIONS");
                route.setMethods(methods);
            }
            //Route result=kongRoute.addRoute(route);
            Route result=kongRoute.addRouteAndJudege(route);
            /*newRoute.setName(route.getName());
            newRoute.setPaths(route.getPaths());
            newRoute.setService(route.getService());
            List<String> methods = route.getMethods();
            methods.add("OPTIONS");
            newRoute.setMethods(methods);
            Route result=kongRoute.addRoute(newRoute);*/

            //添加route成功后需要把缓存中的route信息给删除
            redisUtils.judgeAndRemove(routeRedisKey);

            /**默认开启acl，key-auth插件*/
            /*Map<String, Object> config = new HashMap<>();
            //RandomStringUtils.randomAlphabetic产生10位长度的随机字符串
            //应该是一开始给路由添加acl插件的时候，随便生成一个允许访问的角色
            config.put("allow", Collections.singletonList(RandomStringUtils.randomAlphabetic(10)));
            //都是用内部类
            Plugin acl = new Plugin.Builder("acl")
                    .setRoute(new Plugin.Route(result.getId()))
                    .setConfig(config).builder();
            Plugin keyAuth = new Plugin.Builder("key-auth")
                    .setRoute(new Plugin.Route(result.getId())).builder();
            kongPlugin.addPlugin(acl);
            kongPlugin.addPlugin(keyAuth);*/
            return new Result<>("success",200,"success");
        }catch(IOException e){
            return new Result<>(IO_ERROR, 400, "fail");
        }
    }
    @RequestMapping("/list")
    public Result<List<Route>> listAllRoutes() throws URISyntaxException {
        //判断缓存中有没有，如果有就从缓存中拿
        List<Route> temp= (List<Route>) redisUtils.judgeAndGet(routeRedisKey);
        if(temp!=null){
            return new Result<>(temp,200,"success");
        }else{
            //缓存中没有数据，需要从kong中拿
            try{
                List<Route> routes = kongRoute.listAllRoutes();
                redisUtils.set(routeRedisKey,routes);
                return new Result<>(routes,200,"success");
            }catch(IOException e) {
                e.printStackTrace();
                return new Result<>(null, 200, "error");
            }
        }
    }

    /**
     * 去kong中查指定route的信息
     * @param id
     * @return
     */
    @RequestMapping("/getById")
    public Result<Route> getById(String id) throws URISyntaxException{
        try{
            Route routeById = kongRoute.getRouteById(id);
            return new Result<>(routeById,200,"success");
        }catch (IOException e){
            return new Result<>(null,400,"error");
        }
    }

    /**
     * 去kong中查指定route的信息
     * @param nameOrId
     * @return
     */
    @RequestMapping("/getByNameOrId")
    public Result<Route> getByName(String nameOrId) throws URISyntaxException{
        try{
            Route routeById = kongRoute.getRouteById(nameOrId);
            return new Result<>(routeById,200,"success");
        }catch (IOException e){
            return new Result<>(null,400,"无对应数据");
        }
    }


    /**
     * 删除一个route
     * 删除前需要判断，如果这个Route底下还有绑定的api接口，就不能删除
     * @param id
     * @return
     * @throws URISyntaxException
     */
    @RequestMapping("/delete")
    public Result<String> deleteById(String id) throws URISyntaxException {
        try{
            Route route = kongRoute.getRouteById(id);
            List<String> paths = route.getPaths();
            routePathsMapper.deletePaths(paths);
            routeService.deleteRouteById(id);
            //删除一个route后，还需要把缓存中的route信息删除
            redisUtils.judgeAndRemove(routeRedisKey);
            return new Result<>("success",200,"success");
        }catch(IOException e){
            return new Result<>("error",400,"error");
        }
    }

    /**
     * 查询某个Route下的所有api接口信息
     * @param id
     * @return
     */
    @RequestMapping("/getPageChildInterface")
    public Result<PageInfo<ApiInterfaceWithBLOBs>> getPageChildInterface(String id,String name,Integer pageSize,Integer page){
        PageInfo<ApiInterfaceWithBLOBs> list=routeService.getPageChildInterface(id,name,pageSize,page);
        return new Result<>(list,200,"success");
    }

    @RequestMapping("/update")
    public Result<String> updateRouteById(@RequestBody @Validated Route route) throws URISyntaxException {
        try{
            routeService.updateRouteById(route);
            return new Result<>("success",200,"success");
        }catch(IOException e){
            return new Result<>("error",400,"error");
        }
    }

}
